<?php
// head control
Magnum::importcore('body/item');
Magnum::importcore('utility/stack/manager');
/**
 * body manager
 * @uses Magnum_Utility_Stack_Manager
 * @uses Magnum_Body_Item
 */
class Magnum_Body_Manager extends Magnum_Utility_Stack_Manager
{
    /**
     * the view obj
     * @var Magnum_View
     */
    protected $_view = null;


    /**
     * initialise
     * @param Magnum_View $view the view object
     * @return void
     */
    public function __construct(Magnum_View $view)
    {
        // use view to fit in the stack for this...
        $this->_view = $view;

    }// end Magnum_View


    /**
     * overload so it uses body item instead of normal stack item...
     * get items by $key
     * @param $key the key
     * @param $set if true, set it!
     * @return mixed
     */
    public function get($key, $set = false)
    {
        if (isset($this->_stack[$key])) {
            return $this->_stack[$key];
        }

        if ($set) {
            $this->_stack[$key] = new Magnum_Body_Item($key);
            return $this->_stack[$key];
        }

        return false;

    }// end get


    /**
     * get the path of a view template
     * it goes like this:
     * 1. if in theme, use theme's to override
     * 2. if not in theme, but in extended, use extended
     * 3. otherwise, use core,
     * 4. if not found at all, exit.
     * @param str $src the source name + extension (so other than php it can still work)
     * @return str
     */
    public function _getViewTemplate($src)
    {
        $src = 'views/' . $src;
        // first, use theme...
        $path = Magnum::dir('THEMEDIR') . $src;

        if (!file_exists($path)) {
            $path = Magnum::dir('APPEXT') . $src;
        }

        if (!file_exists($path)) {
            $path = Magnum::dir('APPCORE') . $src;
        }

        if (!file_exists($path)) {
            throw new Magnum_Exception('Template [' . $src . '] not found anywhere.');
        }

        // otherwise, return
        return $path;

    }// end _getViewTemplate


    /**
     * add template
     * @param str $key the key of the template
     */
    public function addTemplate($key = 'body', $template = '', $type = 'APPEND')
    {
        // validate the template first...
        $template = $this->_getViewTemplate($template);

        // set it with special var...
        return $this->set($key, array('src' => $template, 'type' => 'FILE'), $type);

    }// end addTemplate


    /**
     * add src
     * @param str $key the key of the template
     */
    public function addSrc($key = 'body', $template = '', $type = 'APPEND')
    {
        // directly add it...
        return $this->set($key, array('src' => $template, 'type' => 'RAW'), $type);

    }// end addSrc

}// end Magnum_Body_Manager
?>